package com.example.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.mapper.ClassesMapper;
import com.example.springboot.mapper.StudentMapper;
import com.example.springboot.pojo.Student;
import com.example.springboot.pojo.vo.StudentVo;
import com.example.springboot.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.valves.StuckThreadDetectionValve;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseStatus;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @outhor fufeixiang
 * @date 2021-11-16
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;
    //查询所有学生
    @Override
    public List<Student> findAll() {

        //获取所有学生信息
        List<Student> students = studentMapper.selectByExample(null);
        //绑定学生和班级信息
        for (Student stu: students) {
            stu.setCname(classesMapper.selectByPrimaryKey(stu.getCid()).getCname());
        }
        return students;
    }

    @Override
    public PageInfo<Student> search(int page, int pageSize, StudentVo studentVo) {
        //开始分页
        PageHelper.startPage(page,pageSize);
        //创建example实例对象,进行查询
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        //添加查询条件
        if(studentVo != null){
            //姓名不为空
            if(StrUtil.isNotBlank(studentVo.getSname())){
                criteria.andLike("sname","%"+studentVo.getSname()+"%");
            }
            if(studentVo.getCid() != 0){
                criteria.andEqualTo("cid",studentVo.getCid());
            }
        }
        //根据条件开始查询
        List<Student> students = studentMapper.selectByExample(example);
        for (Student stu: students) {
            stu.setCname(classesMapper.selectByPrimaryKey(stu.getCid()).getCname());
        }
        //
        return new PageInfo<Student>(students);
    }
    //添加学生
    @Override
    public void insert(Student student) {
        studentMapper.insert(student);
    }
    //修改学生
    @Override
    public void update(Student student) {
        studentMapper.updateByPrimaryKey(student);
    }
    //删除学生
    @Override
    public void delete(Long[] ids) {
        for (long id:ids) {
            studentMapper.deleteByPrimaryKey(id);
        }

    }


}
